﻿using CommunityToolkit.Mvvm.DependencyInjection;
using Daq.Services;
using Daq.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using Telerik.Windows.Controls;

namespace Daq.Views
{
    /// <summary>
    /// IpAddressSettingView.xaml 的交互逻辑
    /// </summary>
    public partial class IpAddressSettingView : RadWindow
    {
        private readonly ILogger logger;
        private const string ipRegex = @"((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}";
        public IpAddressSettingView(ILogger logger)
        {
            this.logger = logger;
            InitializeComponent();
            //textboxIp.Text = ip;
            textboxNetMask.Text = "255.255.255.0";
        }

        private string model = "";
        private string sn = "";
        private string ip = "";
        public void SetDeviceInfo(string model, string sn, string ip)
        {
            textboxIp.Text = ip;
            this.model = model;
            this.sn = sn;
            this.ip = ip;
        }
        private bool IsValidIp(string text)
        {
            return Regex.IsMatch(text, ipRegex);
        }

        private void CheckIPAddress()
        {
            btnModify.IsEnabled = IsValidIp(textboxIp.Text) && IsValidIp(textboxNetMask.Text);
        }

        private void textboxIp_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckIPAddress();
        }

        private void textboxNetMask_TextChanged(object sender, TextChangedEventArgs e)
        {
            CheckIPAddress();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private async void btnModify_Click(object sender, RoutedEventArgs e)
        {
            busyIndicator.BusyContent = "修改中";
            busyIndicator.IsBusy = true;
            var deviceService = App.Current.Services.GetService<DeviceService>();
            string[] address = new string[]
            {
                textboxIp.Text,
                textboxNetMask.Text
            };
            try
            {
                string ip = textboxIp.Text;
                logger.Information($"修改IP:{ip}");
                var device = deviceService.CreateDaqDevice(model, sn);
                if (device == null) goto exit;
                await device.OpenAsync(this.ip, CancellationToken.None);
                await device.ModifyAddress(address, CancellationToken.None);
                await Task.Delay(500);
                await device.CloseAsync(CancellationToken.None);
                this.DialogResult = true;
                logger.Information($"修改成功");
            }
            catch (Exception ex) 
            {
                this.DialogResult = false;
                logger.Information($"修改失敗：{ex.Message}");
            }
        exit:
            busyIndicator.IsBusy = false;
            this.Close() ;
        }
    }
}
